package com.yeyks.commonReference.append.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存储值
     *
     * @param key
     * @param value
     */
    public Boolean setValue(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("redis报错{}", e.getLocalizedMessage());
            return false;
        }
    }

    /**
     * 存储值（带过期时间,可通过TimeUnit自己设置秒，分，时等）
     *
     * @param key
     * @param value
     */
    public Boolean setValueTimeOut(String key, String value, Integer second) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, second, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("redis报错{}", e.getLocalizedMessage());
            return false;
        }
    }

    /**
     * 存储值（带过期时间,可通过TimeUnit自己设置秒，分，时等）
     *
     * @param key
     * @param value
     */
    public Boolean setValueTimeOut(String key, String value, Integer time, TimeUnit timeUnit) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, time, timeUnit);
            return true;
        } catch (Exception e) {
            log.error("redis报错{}", e.getLocalizedMessage());
            return false;
        }
    }

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public String getValue(String key) {
        try {
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("获取key = {}失败", key);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * value值实现自增
     *
     * @param key
     * @return
     */
    public void increValue(String key) {
        try {
            stringRedisTemplate.opsForValue().increment(key, 1);
        } catch (Exception e) {
            log.error("value值实现自增key = {}失败", key);
            e.printStackTrace();
        }
    }

    /**
     * 删除值
     *
     * @param key
     * @return
     */
    public Boolean deleteKey(String key) {
        try {
            stringRedisTemplate.delete(key);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * //根据key获取过期时间并换算成指定单位
     *
     * @param key
     * @return
     */
    public Long getExpire(String key) {
        return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在，返回boolean值
     *
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

}
